/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ModuloConfiguracion;

import Modelo.Cargo;
import Modelo.DAL.Cargo_DAO;
import Acceso.Security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author alb3rto
 */
public class agregarCargoAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";
    private static final String[] ALLOWED = {"Administrador", "Gestionar Cargos y Puestos de Trabajo"};

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {


        if (!Security.validateSession(request, ALLOWED)) {
            Security.privilegeError(response);
            return mapping.findForward("errorPriv");
        }

        agregarCargoForm formBean = (agregarCargoForm) form;
        String nombre = formBean.getNombreCargo(); //Obligatorio
        String descripcion = formBean.getDescripcion(); //Obligatorio

        ActionErrors errors = new ActionErrors();
        boolean error = false;
        //Verificaciones del formulario de implemento
        if (nombre == null || nombre.equals("")) {
            errors.add("nombre_cargo_requerido", new ActionMessage("errors.nombre_cargo_requerido"));
            saveErrors(request, errors);
            error = true;
        }
        if (descripcion == null || descripcion.equals("")) {
            errors.add("descripcion_cargo_requerido", new ActionMessage("errors.descripcion_cargo_requerido"));
            saveErrors(request, errors);
            error = true;
        }

        if (error) {
            return mapping.findForward(FAILURE);
        }

        Cargo c = new Cargo(nombre, descripcion);
        if (!Cargo_DAO.insertarCargo(c)) {
            errors.add("cargo_fallido", new ActionMessage("errors.cargo_fallido"));
            saveErrors(request, errors);
            return mapping.findForward(FAILURE);
        }
        return mapping.findForward(SUCCESS);
    }
}
